package com.jms.fu.model.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.jms.fu.exception.DAOException;

public class AppDownDAO {
	Connection conn = null;
	PreparedStatement pStm = null;
	Statement stm = null;
	ResultSet rs = null;
	public void addAppToUsername(String username,int appid,String downVersion) throws DAOException{
		String sql = "INSERT INTO tb_AppDown(userID,appID,datedownload,downVersion) VALUES(?,?,?,?)";
		try {
			conn = ConnectionFactory.getConnection();
			pStm = conn.prepareStatement(sql);
			pStm.setString(1, username);
			pStm.setInt(2, appid);
			pStm.setDate(3, new Date(new java.util.Date().getTime()));
			pStm.setString(4, downVersion);
			pStm.executeUpdate();
		} catch (DAOException | SQLException e) {
			throw new DAOException(e.getMessage());
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pStm != null) {
					pStm.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				throw new DAOException(e.getMessage());
			}
		}
	}
	public ArrayList<String> getAppOwnByUsername(String username) throws DAOException{
		ArrayList<String> listAppId = new ArrayList<String>();
		String sql = "SELECT appId FROM tb_AppDown WHERE userID = ?";
		try {
			conn = ConnectionFactory.getConnection();
			pStm = conn.prepareStatement(sql);
			pStm.setString(1, username);
			rs = pStm.executeQuery();
			while(rs.next()){
				listAppId.add(rs.getString(1));
			}
			
		} catch (DAOException | SQLException e) {
			throw new DAOException(e.getMessage());
		}finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pStm != null) {
					pStm.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				throw new DAOException(e.getMessage());
			}
		}
		return listAppId;
	}
	
	public boolean checkAppOwnByUsername(String username,int appid) throws DAOException{
		ArrayList<String> listAppId = new ArrayList<String>();
		String sql = "SELECT appId FROM tb_AppDown WHERE userID = ? AND appID = ?";
		try {
			conn = ConnectionFactory.getConnection();
			pStm = conn.prepareStatement(sql);
			pStm.setString(1, username);
			pStm.setInt(2, appid);
			rs = pStm.executeQuery();
			if(rs.next()){
				return true;
			}
			
		} catch (DAOException | SQLException e) {
			throw new DAOException(e.getMessage());
		}finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pStm != null) {
					pStm.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				throw new DAOException(e.getMessage());
			}
		}
		return false;
	}
	
}
